from rest_framework import serializers
from apps.goods.models import SKUImage,SKU


class SKUImageModelSerializer(serializers.ModelSerializer):


    class Meta:
        model = SKUImage
        fields = ('sku', 'image', 'id')

    def update(self, instance, validated_data):
        image_data = validated_data.get('image').read()
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)
        if result['Status'] !='Upload successed.':
            raise serializers.ValidationError('上传失败')
        file_id = result.get('Remote file_id')
        instance.image = file_id
        instance.save()
        return instance


class ImageSKUModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['id','name']